<?php

namespace App\Service\VendorClient\Shopbaison;

use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Model\PssModel\ServiceConfig;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

/***
 * 百胜ME3上游对接
 * @author: hj
 */
class ShopbaisonApiClient extends BaseService {
    //供应商编号
    const SUPPLIER_CODE = 'shopbaison';

    //配置文件
    private $config = [];

    public function __construct($apiBody = []) {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     * @param array $params
     * @return array
     */
    public function createOrder($param = []) {
        $orderInfo   = $param['supplierOrder'];
        $goodsList   = $param['orderGoods'];
        $order       = $param['order'];
        $binfo       = $param['binfo'];
        $companyInfo = $param['companyInfo'];
        $order_sn    = $orderInfo['supplier_dsn'];
        //支付流水号
        $pay_sn = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'];
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);
        //获取下单商品信息
        $palceOrderGoods = [];
        foreach ($goodsList as $key => $item) {
            //卖价
            $price = $item['price'];
            //商品购买规格数量
            $spec_num = $item['spec_num'];//1
            //商品购买数量
            $quantity = $item['quantity'];//2
            //实际购买数量(下单数量 X 起售数量)
            $buyAcount = $spec_num * $quantity;//2
            //商品税率
            $tax      = $item['tax_rate'];//0.0910
            $tax_rate = bcadd((string)$tax, '1.0000', 4);//1.0910
            //下单商品组
            $goodsInfo         = [
                'sku'          => trim($item['supplier_skucode']),//商品SKU编码
                'goods_sn'     => trim($item['supplier_commodity_key']),//商品货号
                'goods_name'   => $item['goods_name'],//商品名称
                'shop_price'   => $price,//商品售价
                'goods_price'  => $price,//商品实际成交价
                'goods_number' => $quantity,//商品数量
            ];
            $palceOrderGoods[] = $goodsInfo;
        }
        $requestParam = [
            'deal_code'         => $order_sn,//平台交易号（外部系统对接此字段为准）
            'lylx'              => 0,//订单来源平台 0 "后台"
            'sd_code'           => $this->config['sdCode'],//店铺代码
            'user_name'         => $this->config['userName'],//会员名称
            'pay_code'          => '000',//支付方式代码
            'receiver_name'     => $orderInfo['receive_name'],//收货人
            'receiver_country'  => '中国',//收货人国家
            'receiver_province' => $orderInfo['province'],//收货人省份
            'receiver_city'     => $orderInfo['city'],//市
            'receiver_district' => $orderInfo['district'],//区
            'receiver_addr'     => $orderInfo['receive_address'],//区
            'receiver_address'  => $orderInfo['province'] . '.' . $orderInfo['city'] . '.' . $orderInfo['district'] . '.' . $orderInfo['receive_address'],//收货人的详细地址 省市区街道详细地址用点隔开
            'receiver_mobile'   => $orderInfo['recveive_phone'],//收货人的手机号码
            'add_time'          => $order_time,//订单下单时间（YYYY-MM-DD HH:II:SS）
            'pay_time'          => $pay_time,//订单支付时间（YYYY-MM-DD HH:II:SS）
            'pay_status'        => 1,//付款状态（0:未付款;1:已付款）
            'shipping_fee'      => $deliver_money,//运费
            'order_amount'      => $orderInfo['real_total_money'],//应付金额
            'payment'           => $orderInfo['real_total_money'],//已付金额
            'is_cod'            => 0,//交易类型 0:款到发货;1:货到付款
            'buy_msg'           => $orderInfo['order_remark'] ?? '',//客户留言
            'seller_msg'        => $orderInfo['order_remark'] ?? '',//商家备注
            'items'             => $palceOrderGoods,
        ];
        $data         = [
            'method' => 'createOrder',
            'data'   => $requestParam,
        ];
        return $this->execute($data);
    }

    /**
     * 申请退款接口
     * @param $data
     * @return array
     */
    public function orderAfterSale($params = []) {
        $data = [
            'method' => 'orderAfterSale',
            'data'   => [
                'sell_return_record' => [
                    'deal_code' => $params['supplierOrder']['supplier_dsn'],//平台交易号（外部系统对接此字段为准）
                    'return_ck_code' => $this->config['returnCkCode'],//退货仓库代码
                    'return_kw_code' => $this->config['returnKwCode'],//退货库位代码
                    'return_type' => 1,//退单类型（1退货2追件3拒收）
                ]
            ],
        ];
        return $this->execute($data);
    }

    /**
     * 查询物流
     * @param array $orderInfo
     * @return array
     */
    public function queryOrderExpress($orderInfo){
        $data = [
            'method' => 'orderExpress',
            'data'   => [
                'deal_code' => $orderInfo['supplier_dsn']
            ],
        ];
        return $this->execute($data);
    }

    /**
     * 签名
     * @param array $tsp
     * @return string
     */
    public function sign($param) {
        ksort($param);
        $strA = '';
        foreach ($param as $k => $v) {
            $strA .= "{$k}{$v}";
        }
        $strB = $this->config['appSecret'] . $strA . $this->config['appSecret'];
        $strC = md5($strB);
        return strtoupper($strC);
    }

    /**
     * CURL请求
     * @param $params
     * @return array
     */
    public function execute($param = []) {
        $method = $param['method'];
        $data   = $param['data'];
        if (!isset($this->config[$method])) {
            return Normal::returnCode(Normal::FAIL, "请求方法名称未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "接口请求数据不能为空");
        }
        $baseUrl = $this->config['baseUrl'] ?? '';
        if (empty($baseUrl)) {
            return Normal::returnCode(Normal::FAIL, "接口请求地址不能为空");
        }
        $pushData         = [
            'method'      => $this->config[$method],
            'format'      => 'json',
            'key'         => $this->config['appKey'],
            'timestamp'   => date("Y-m-d H:i:s"),
            'v'           => '2.0',
            'sign_method' => 'md5',
            'data'        => json_encode($data, JSON_UNESCAPED_UNICODE),
        ];
        $pushData['sign'] = $this->sign($pushData);
        $parameter        = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $baseUrl,
                'data'   => $pushData,
                'method' => 'post',
                'format' => 'x-www-form-urlencoded',
                'header' => [],
            ],
        ];
        if (in_array($param['method'], ['orderExpress'])) {
            $resTask = TaskWorker::instance()->addTask($parameter, 'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask = current($resTask);
        $result  = @json_decode($resTask['response']['result'], true);

        if (isset($result['status']) && $result['status'] == 1) {
            return Normal::returnCode(Normal::SUC, "操作成功", $result);
        }
        $msg = $result['message'] ?? '请求失败';
        return Normal::returnCode(Normal::FAIL, $msg, $result);
    }

}